package com.futvan.z.system.zcode;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Service;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.SuperService;
import com.futvan.z.framework.core.z;
@Service
public class ZcodeService extends SuperService{
	
	/**
	 * 更新字典关联信息
	 * @return
	 */
	public Result update_z_code_allkeyvalue_columns() {
		Result result = new Result();
		try {
			//获取所有字典信息
			List<z_code> list = sqlSession.selectList("z_code_select");
			for (z_code c : list) {
				
				z_code new_c = new z_code();
				new_c.setZid(c.getZid());
				
				//获取所有Key Value键值对
				String all_key_value = getAll_key_value(c.getZ_number());
				new_c.setAll_key_value(all_key_value);
				
				//获取所有引用字段ID
				String columns = getColumns(c.getZ_number());
				new_c.setColumns(columns);
				
				int num = sqlSession.update("z_code_update_zid", new_c);
				if(num!=1) {
					z.Exception("更新字典表关联信息出错|更新记录数："+num);
				}
			}
			result.setCode(Code.SUCCESS);
			result.setMsg("执行成功");
		} catch (Exception e) {
			result.setCode(Code.ERROR);
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	private String getColumns(String z_number) {
		StringBuffer rinfo = new StringBuffer();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT t.table_id,t.table_title,tc.column_id,tc.column_name ");
		sql.append("FROM z_form_table_column tc ");
		sql.append("LEFT JOIN z_form_table t ON tc.pid = t.zid ");
		sql.append("WHERE tc.p_code_id = '"+z_number+"'");
		List<HashMap<String,String>> list = selectList(sql.toString());
		for (HashMap<String, String> map : list) {
			String table_id = map.get("table_id");
			String table_title = map.get("table_title");
			String column_id = map.get("column_id");
			String column_name = map.get("column_name");
			rinfo.append(table_title+"●"+column_name+" ["+table_id+"●"+column_id+"]"+" | ");
		}
		return rinfo.toString();
	}

	/**
	 * 获取所有Key Value键值对
	 * @param zid
	 * @return
	 */
	private String getAll_key_value(String z_number) {
		StringBuffer rinfo = new StringBuffer();
		z_code c = z.code.get(z_number);
		List<z_code_detail> dlist = c.getZ_code_detail_list();
		for (z_code_detail cd : dlist) {
			rinfo.append(cd.getZ_key()+" = "+cd.getZ_value()+" | ");
		}
		return rinfo.toString();
	}
}
